import wx

from .xrc.main_xrc import xrcMain

class MainWindow(xrcMain):
    """Main application window.

    Shows plugins in notebook tabs.

    """

    _app = _windowProps = None
    _configSectionName = "MainWindow"

    def __init__(self, parent, application):
        super(MainWindow, self).__init__(parent)
        self._app = application
        self._windowProps = self._app.getConfigSection(
            self._configSectionName, {})
        self._restorePos()
        self._openAllPlugins()

    def _restorePos(self):
        """Restore window position"""
        _state = self._windowProps.get("State", {})
        _size = _state.get("Size", None)
        _pos = _state.get("Position", None)
        if _size:
            (_w, _h) = (_size["width"], _size["height"])
        else:
            (_w, _h) = self.GetSize()
        if _pos:
            (_x, _y) = (_pos["X"], _pos["Y"])
        else:
            (_x, _y) = self.GetPosition()

        # now we need to check that window is in desktop.
        # (Otherwise, it could be restored outside of visible area
        #  e.g. when screen resolution has changed)
        (_deskW, _deskH) = wx.DisplaySize()
        # fix position
        _maxX = max(0, _deskW - _w)
        if _x > _maxX:
            _x = _maxX
        _maxY = max(0, _deskH - _h)
        if _y > _maxY:
            _y = _maxY
        # fix size (actually, it will shrink window
        # to screen size -- due to position fix realization)
        _maxW = min(_deskW, _deskW - _x)
        if _w > _maxW:
            _w = _maxW
        _maxH = min(_deskH, _deskH - _y)
        if _h > _maxH:
            _h = _maxH

        self.SetPosition((_x, _y))
        self.SetSize((_w, _h))


    def _savePos(self):
        """Save window position in local config dictionary."""
        _pos = self.GetPosition()
        _size = self.GetSize()
        self._windowProps["State"] = {
            "Size": {
                "width": _size[0],
                "height": _size[1],
            },
            "Position": {
                "X": _pos[0],
                "Y": _pos[1],
            },
        }

    def _openAllPlugins(self):
        """Open all plugins thought to be opened."""
        self.pagebook.DeleteAllPages()
        for _name in self._app.getOpenedPlugins():
            self.openPlugin(_name)

    def openPlugin(self, name):
        """Open specific plugin with given name."""
        _panel = self._app.getPlugin(name, self.pagebook)
        self.pagebook.AddPage(_panel, _panel.name)

    def OnWindow_destroy(self, evt):
        self._savePos()
        self._app.setConfigSection(
            self._configSectionName,
            self._windowProps
        )

# vim: set sts=4 sw=4 et :
